from .view import DevopsView
from . import schema
from fastapi import APIRouter, Depends, Security
from package.connector.sql_db import db
from package.fastapi import permission


router_devops = APIRouter(prefix='/devops', tags=['运维管理'])
router_meta = {'module': '运维管理', 'sub_module': '运维对象'}


@router_devops.get('/', response_model=schema.PageDevopss, openapi_extra=router_meta, name='devops_list_get',
                 summary='运维对象列表')
def devops_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['devops:read'])):
    return DevopsView.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_devops.post('/', response_model=schema.DevopsOut, openapi_extra=router_meta, name='devops_post', summary='运维对象创建')
def devops_post(body: schema.CreateDevops,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['devops:write'])):
    return DevopsView.create_item(session, body=body.dict())


@router_devops.get('/{id}', response_model=schema.DevopsOut, openapi_extra=router_meta, name='devops_get',
                 summary='运维对象详情')
def devops_get(id: str,
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['devops:read'])):
    return DevopsView.get_item(session, filter_=[DevopsView.id == id])


@router_devops.patch('/{id}', response_model=schema.DevopsOut, openapi_extra=router_meta, name='devops_patch',
                   summary='运维对象修改')
def devops_patch(id: str,
               body: schema.EditDevops,
               session=Depends(db.get_session),
               user=Security(permission.security, scopes=['devops:write'])):
    return DevopsView.update_item(session, filter_=[DevopsView.id == id], update=body.dict(exclude_unset=True))


@router_devops.delete('/', openapi_extra=router_meta, name='devops_delete', summary='运维对象删除')
def devops_delete(body: schema.BatchId,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['devops:write'])):
    return {'count': DevopsView.delete_items(session, filter_=[DevopsView.id.in_(body.ids)])}
